import json
from django.contrib.auth import login, logout, authenticate
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from .models import Books, Record


# Create your views here.
class LoginView(View):
    # 登录接口
    def post(self, request):
        """
        # 获取参数
        request.POST:获取表单参数
        request.body:获取json参数
        """
        # username= request.POST.get("username")
        # password = request.POST.get("password")
        # 如果是json格式的参数
        # request.body 获取json参数
        # params = json.loads(request.body.decode())

        # 兼容
        params = request.POST if len(request.POST) else json.loads(request.body.decode())
        username = params.get("username")
        password = params.get("password")

        # 校验账号密码是正确
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return JsonResponse({"code": 1000, "message": "登陆成功"})
        else:
            return JsonResponse({"code": 2001, "message": "登录失败"})


class Logout(View):
    """退出登录"""
    def get(self, request):
        logout(request)
        return JsonResponse({"code": 1000, "message": "已注销用户登录"})



"""
需求：给图书管理所有的接口加上登录认证
    需要登陆之后才能访问
"""
class BookView(View):
    """图书管理的接口"""
    def get(self, request):
        """获取图书"""
        # 判断用户是否登录
        if not request.user.is_authenticated:
            return JsonResponse({"code": 2002, "message": "认证失败， 你未能登录， 没有访问权限"})

        bs = Books.objects.all()
        # 获取所有的图书信息(通过列表推导式获取)
        data = [{"id": b.id, "name": b.name, "status": b.status} for b in bs]
        return JsonResponse({"code": 1000, "message": "获取成功", "data": data})

    def post(self, request):
        """添加图书"""
         # 1.登录状态认证
        if not request.user.is_authenticated:
            return JsonResponse({"code": 2002, "message": "认证失败， 你未能登录， 没有访问权限"})
         # 2.获取参数(同时支持json和表单参数)
        params = request.POST if len(request.POST) > 0 else json.loads(request.body.decode())
        id = params.get("id")
        name = params.get("name")
        # 3.参数效验是否为空
        if not (id and name):
            return JsonResponse({"code": 2001, "message": "书籍的id和name均不能为空"})

        if not isinstance(id, str):
            return JsonResponse({"code": 2001, "message": "参数id只能为字符串类型"})

        if not isinstance(name, str):
            return JsonResponse({"code": 2001, "message": "参数name只能为字符串类型"})

        # 添加图书
        try:
            Books.objects.create(id=id, name=name)

        except Exception as e:
            # 如果id存在则会报错
            return JsonResponse({"code": 2001, "message": "书籍已存在"})

        else:
            return JsonResponse({"code": 1000, "message": "添加成功"})

    def delete(self, request):
        """删除图书"""
        # 1. 效验用户是否登录
        # 1.登录状态认证
        if not request.user.is_authenticated:
            return JsonResponse({"code": 2002, "message": "认证失败， 你未能登录， 没有访问权限"})

        # 2.获取参数(删除书籍id)
        id = request.GET.get("id")
        if not id:
            return JsonResponse({"code": 2001, "message": "删除书籍id时必填项"})

        # 3.效验参数是否有效
        try:
            book = Books.objects.get(id=id)

        except Exception as e:
            return JsonResponse({"code": 2001, "message": "传入的书籍id有误"})

        else:
        # 4.删除图书信息
            book.delete()
            return JsonResponse({"code": 1000, "message": "删除成功"})

class RecordView(View):
    """出借图书和归还图书"""
    def post(self, request):
        # 获取图书信息
        # 1. 登录权限验证
        if not request.user.is_authenticated:
            return JsonResponse({"code": 2002, "message": "认证失败， 你未能登录， 没有访问权限"})
        # 2. 获取参数
        params = request.POST if len(request.POST) > 0 else json.loads(request.body.decode())
        book_id = params.get("book")
        name = params.get("name")
        # 3. 参数效验
        # 效验参数是否为空
        if not(book_id and name):
            return JsonResponse({"code": 2001, "message": "书籍编号和借书人name均不能为空"})
        # 效验书籍的编号是否正确
        try:
            book = Books.objects.get(id=book_id)
        except Exception as e:
            return JsonResponse({"code": 2001, "message": "书籍编号, 未能找到对应的书籍"})
        # 效验书籍的状态是否已经出借
        if book.status:
            return JsonResponse({"code": 2001, "message": "书籍已经借出，请确认书籍编号是否出错"})
        # 效验借书人的名字类型
        if not isinstance(name, str):
            return JsonResponse({"code": 2001, "message": "借书人的名字必须为字符串类型"})

        # 4. 借书操作(开启事务)
        # 修改书籍的状态
        with transaction.atomic():
            book.status = True
            book.save()
            # 添加一条借书记录
            Record.objects.create(book=book, name=name)
        return JsonResponse({"code": 1000, "message": "图书出借成功"})



def index(request):
    context = {
        'title': 'Welcome to Django',
        'message': 'This is a sample message.'
    }
    return render(request, "book/index.html", context)










